//
//  PreBookViewController.m
//  xingfugangwan
//
//  Created by rainday on 14/12/25.
//  Copyright (c) 2014年 rainday. All rights reserved.
//

#import "PreBookViewController.h"
#import "PreBookTableViewCell.h"
#import <ReactiveCocoa.h>
#import <RACEXTScope.h>
#import <AFNetworking.h>
#import <MBProgressHUD.h>
#import "InputViewController.h"
#import "NetIP.h"
#import "UMSCashierPlugin.h"

#define CATEGORY @[@"结婚",@"回门",@"合办",@"生日",@"其他"]

@interface PreBookViewController ()<UITableViewDelegate,UITableViewDataSource,InPutViewProtocol,UIAlertViewDelegate,UMSCashierPluginDelegate>

@property (nonatomic ,readonly) NSString *category;

@property (nonatomic ,strong) NSDictionary *dictionary;

@property (nonatomic,weak) IBOutlet UIButton *preButton;
@property (nonatomic,weak) IBOutlet UITableView *tableView;


@property (nonatomic ,strong) NSArray *styleArray;
@property (nonatomic ,strong) NSArray *salemanArray;
@property (nonatomic,strong)  NSMutableDictionary *postDic;
@property (nonatomic ,strong) NSString *umsOrerId;


- (IBAction)addOrder:(id)sender;

@end

static NSString *reuseIdentify1 = @"cell";

@implementation PreBookViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil category:(NSString *)category{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _category = category;
        
        
        
    }
    
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _postDic = [[NSMutableDictionary alloc] init];
    // Do any additional setup after loading the view from its nib.
    _tableView.layer.cornerRadius = 5.0f;
    _tableView.layer.masksToBounds = YES;
    self.navigationItem.title = [NSString stringWithFormat:@"请填写%@预约单",[_category isEqualToString:@"其他"]?@"":_category];
    
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    NSDictionary * dict=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor,[UIFont systemFontOfSize:18],UITextAttributeFont, nil];

    self.navigationController.navigationBar.titleTextAttributes = dict;
    
    [_preButton setBackgroundImage:[UIImage imageNamed:@"yuyue3"] forState:UIControlStateHighlighted];
    
    
    _tableView.backgroundColor = [UIColor clearColor];
    
    NSArray *wedding = @[@"新郎",@"新娘",@"结婚时间",@"结婚地址",@"联系人",@"电话",@"邮箱",@"负责人",@"主题",@"色调",@"预付款",@"付款方式"];
    NSArray *backdoor = @[@"新郎",@"新娘",@"回门时间",@"回门地址",@"联系人",@"电话",@"邮箱",@"负责人",@"主题",@"色调",@"预付款",@"付款方式"];
    NSArray *weddingAndBackdoor = @[@"新郎",@"新娘",@"结婚时间",@"结婚地址",@"回门时间",@"回门地址",@"联系人",@"电话",@"邮箱",@"负责人",@"主题",@"色调",@"预付款",@"付款方式"];
    NSArray *birthday = @[@"寿星",@"宴会时间",@"宴会地址",@"联系人",@"电话",@"邮箱",@"负责人",@"主题",@"色调",@"预付款",@"付款方式"];
    NSArray *other = @[@"主角",@"宴会时间",@"宴会地址",@"联系人",@"电话",@"邮箱",@"负责人",@"主题",@"色调",@"预付款",@"付款方式"];
    
    _dictionary = [NSDictionary dictionaryWithObjectsAndKeys:wedding,@"结婚",backdoor,@"回门",weddingAndBackdoor,@"合办",birthday,@"生日",other,@"其他", nil];

  

}


- (void)setSalemanArray:(NSArray *)salemanArray
{
    _salemanArray = salemanArray;
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/




- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 64.0;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *array = [_dictionary objectForKey:_category];
    return [array count];
    
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentify1];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuseIdentify1];
    }
    
    NSArray *array = [_dictionary objectForKey:_category];
    if ([array count]> indexPath.row) {
        NSString *leftText = array[indexPath.row];
        
        cell.textLabel.text = leftText;
        cell.detailTextLabel.text = [_postDic objectForKey:cell.textLabel.text];
            
        
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 20;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    [view setBackgroundColor:[UIColor clearColor]];
    return view;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    InputViewControllerTextFieldStyle style = InputViewControllerTextFieldNormal;

    if ([cell.textLabel.text hasSuffix:@"时间"]) {
        style = InputViewControllerTextFieldDate;
    
    }
    
    if ([cell.textLabel.text hasSuffix:@"地址"]) {
        style = InputViewControllerTextFieldHotel;
        
    }
    
    if ([cell.textLabel.text hasSuffix:@"负责人"]) {
        style = InputViewControllerTextFieldSaleMan;
    }
    
    if ([cell.textLabel.text hasSuffix:@"方式"]) {
        style = InputViewControllerTextFieldPayStyle;
    }
    if ([cell.textLabel.text hasSuffix:@"款"]) {
        style = InputViewControllerTextFieldPrice;
    }
    
    InputViewController *inputVC = [[InputViewController alloc] initWithNibName:@"InputViewController" bundle:nil  textFieldText:cell.detailTextLabel.text textFieldPlaceholder:cell.textLabel.text textFieldStyle:style];
    
    inputVC.delegate = self;
    
    
    [self.navigationController pushViewController:inputVC animated:YES];
}


- (void)addOrder:(id)sender
{
    
    NSArray *keyArray = [_postDic allKeys];
    if ([keyArray count ] < [[_dictionary objectForKey:_category] count]) {
        return;
    }
    for (id object in _postDic) {
        
        
        
        if ([[_postDic objectForKey:object] isEqualToString:@""]) {
            //此处提醒
            MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
            hud.labelText = @"表单填写不完成，请继续";
            [self.view addSubview:hud];
            [hud showAnimated:YES whileExecutingBlock:^{
                sleep(1);
            }];
        
            
            return;
        }
        
        
        
        
    }
    
    [_postDic setObject:_category forKey:@"category"];
   
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    id token = [userDefaults objectForKey:@"token"];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    [manager.requestSerializer setValue:[NSString stringWithFormat:@"Token %@",token] forHTTPHeaderField:@"Authorization"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
  
 
    
    @weakify(self)
    [manager POST:[[NetIP shareNetAddress] getAddOrderURLString] parameters:_postDic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        
        @strongify(self)
        if ([[responseObject objectForKey:@"status"] isEqualToString:@"success"]) {
            [self performSelectorOnMainThread:@selector(showSucess:) withObject:[responseObject objectForKey:@"orderid"] waitUntilDone:YES];
        }else{
        
        
        }
        
        
        
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error");
    }];

    
    
}

- (void)showSucess:(NSString *)orderid
{
    NSString *payStyle = [_postDic objectForKey:@"付款方式"];
    if ([payStyle hasPrefix:@"现金"]) {
        NSString *messageString = [NSString stringWithFormat:@"预约成功,请支付现金"];
        UIAlertView *alterView = [[UIAlertView alloc] initWithTitle:orderid message:messageString delegate:self cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
        [alterView show];
    }else{
    
        NSString *messageString = [NSString stringWithFormat:@"预约成功,请您刷卡"];
        UIAlertView *alterView = [[UIAlertView alloc] initWithTitle:orderid message:messageString delegate:self cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
        [alterView show];
    
    }
    
   
    
    
    
    
    
}



-(void)refresh{
    [_tableView reloadData];
    
}

- (void)inputViewController:(InputViewController *)inputViewController didPopWithString:(NSString *)string andKey:(NSString *)key
{
    
    
    [inputViewController.navigationController popViewControllerAnimated:YES];
    [_postDic setObject:string forKey:key];
    [_tableView reloadData];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if ([alertView.message hasSuffix:@"支付现金"]) {
         [_delegate preBookViewController:self didAddOrder:nil];
        return;
    }
    //刷卡支付
    [UMSCashierPlugin bookOrder:@"1" MerorderId:alertView.title MerOrderDesc:@"预约订单支付" BillsMID:@"001584056912078" BillsTID:@"20780003" operator:nil Delegate:self ProductModel:NO];
    
 
}


- (void)onUMSBookOrderResult:(NSDictionary *)dict{
    if ([[dict objectForKey:@"resultStatus"] isEqualToString:@"success"]) {
        _umsOrerId = [dict objectForKey:@"orderId"];
        [UMSCashierPlugin setupDevice:@"001584056912078" BillsTID:@"20780003" WithViewController:self Delegate:self ProductModel:NO];
    }

}

- (void)onUMSSetupDevice:(BOOL)resultStatus resultInfo:(NSString *)resultInfo withDeviceId:(NSString *)deviceId{
    [UMSCashierPlugin payOrder:_umsOrerId BillsMID:@"001584056912078" BillsTID:@"20780003" WithViewController:self Delegate:self SalesSlipType:SalesSlipType_AUTO PayType:PayType_EPOS ProductModel:NO];

}
-(void)onPayResult:(PayStatus) payStatus PrintStatus:(PrintStatus) printStatus withInfo:(NSDictionary *)dict{
//    PayStatus_PAYSUCCESS,              //交易成功
//    PayStatus_PAYFAIL,                 //交易失败
//    PayStatus_PAYTIMEOUT,              //交易超时
//    PayStatus_PAYCANCEL,               //交易取消
//    
//    PayStatus_VOIDSUCCESS,              //撤销成功
//    PayStatus_VOIDFAIL,                 //撤销失败
//    PayStatus_VOIDTIMEOUT,              //撤销超时
//    PayStatus_VOIDCANCEL
    
    switch (payStatus) {
        case PayStatus_PAYFAIL:
            
            break;
        case PayStatus_PAYCANCEL:
            break;
        case PayStatus_PAYSUCCESS:
            
            [self dismissViewControllerAnimated:YES completion:nil];
            return;
            break;
        default:
            break;
    }
}

@end
